#!/usr/bin/env node
require('colors')
var run      = require('child_process').spawn
  , file     = require('utilise/file')
  , is       = require('utilise/is')
  , yaml     = require('js-yaml').safeLoad
  , popper   = require('.')
  , argv     = require('minimist')(process.argv.slice(2))
  , port     = argv.p || argv.port
  , browsers = argv.b || argv.browsers
  , tests    = argv.t || argv.tests
  , help     = argv.h || argv.help
  , notunnel = argv.n || argv.notunnel
  , timeout  = argv.l || argv.timeout 
  , runner   = argv.r || argv.runner 
  , farm     = argv.f || argv.farm 
  , exists   = require('fs').existsSync
  , script   = exists('popper.js')
  , config   = exists('.popper')     ? yaml(file('.popper'))
             : exists('popper.yml')  ? yaml(file('popper.yml'))
             : exists('.popper.yml') ? yaml(file('.popper.yml'))
             : {}

if (help) return usage()
if (browsers) config.browsers = is.str(browsers) ? browsers.split(',') : []
if (tests) config.tests = tests
if (port) config.port = port
if (notunnel) config.notunnel = true
if (timeout) config.timeout = timeout
if (runner) config.runner = runner
if (farm) config.farm = farm
  
return script ? run('sh', ['-c', 'node popper.js'], { stdio: 'inherit' })
     : popper(config) 

function usage(){
  console.error('')
  console.error(' usage: popper')
  console.error('')
  console.error(' options:')
  console.error('    -b, --browsers: browser to spawn and run tests on, defaults to none')
  console.error('    -t, --test: command to generate test bundle, defaults to "browserify test.js"')
  console.error('    -p, --port: port to run on, defaults to 1945')
  console.error('    -w, --watch: files to watch for changes, defaults to .')
  console.error('    -n, --notunnel: disable opening tunnel, defaults to open')
  console.error('    -l, --timeout: maximum time to wait in ci mode for results, defaults to POPPER_TIMEOUT or 20000')
  console.error('    -r, --runner: the runner to use, either mocha or tape, defatuls to mocha')
  console.error('    -f, --farm: the remote browser farm to spawn browsers in, defaults to browserstack')
  process.exit(1)
}
